package utilities;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xslf.model.geom.Path;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;



/**
 * @author Idan
 * exports data into Excel files
 */
public class ExcelWriter
{
	
	/**
	 * Writes table data to an excel file
	 * @param table table data to export
	 * @param path path to save the file
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void writeToExcell(JTable table, String path) throws FileNotFoundException, IOException
	{
	    new WorkbookFactory();
	    Workbook wb = new XSSFWorkbook(); //Excell workbook
	    Sheet sheet = wb.createSheet(); //WorkSheet
	    Row row = sheet.createRow(2); //Row created at line 3
	    TableModel model = table.getModel(); //Table model

	    // attempt to create folder
	    
	    File directory = new File("./Reports");
	    
	    directory.mkdirs();
	   

	    Row headerRow = sheet.createRow(0); //Create row at line 0
	    for(int headings = 0; headings < model.getColumnCount(); headings++)
	    { //For each column
	        headerRow.createCell(headings).setCellValue(model.getColumnName(headings));//Write column name
	    }

	    for(int rows = 0; rows < model.getRowCount(); rows++)
	    { //For each table row
	        for(int cols = 0; cols < table.getColumnCount(); cols++)
	        { //For each table column
	            row.createCell(cols).setCellValue(model.getValueAt(rows, cols).toString()); //Write value
	        }

	        //Set the row to the next one in the sequence 
	        row = sheet.createRow((rows + 3)); 
	    }
	    wb.write(new FileOutputStream(path));//Save the file     
	}
	
	
	/**
	 * Creates an empty excel file
	 * @param filename filename for the excel file
	 */
	public static void CreateExlFile(String filename)
	{
       {
        try
        {
        
        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFSheet sheet =  workbook.createSheet();  

        FileOutputStream fileOut =  new FileOutputStream(filename);
        workbook.write(fileOut);
        fileOut.close();
     

        }
        catch ( Exception ex ) 
        {
          

        }
       }
	}
         
         

}
